#include "logindialog.h"
#include <QVBoxLayout>
//#include <QHBoxLayout>
#include <QMessageBox>
#include "utils.h"

LoginDialog::LoginDialog(QWidget *parent, SqlOperator *sqlOperator)
    : QDialog(parent), m_sqlOperator(sqlOperator)
{
    setWindowTitle(tr("用户登录"));
    setFixedSize(300, 180);
    setupUI();

}

LoginDialog::~LoginDialog()
{
}

void LoginDialog::setupUI()
{
    widget_view = new Widget();
    // 创建控件
    m_usernameEdit = new QLineEdit(this);
    m_passwordEdit = new QLineEdit(this);
    m_loginBtn = new QPushButton(tr("登录"), this);
    m_cancelBtn = new QPushButton(tr("取消"), this);

    m_passwordEdit->setEchoMode(QLineEdit::Password);
    m_loginBtn->setObjectName("registerBtn"); // 复用注册按钮样式
    m_cancelBtn->setObjectName("cancelBtn");

    // 设置密码框属性
    m_passwordEdit->setEchoMode(QLineEdit::Password);

    // 创建表单布局
    QFormLayout *formLayout = new QFormLayout();
    formLayout->addRow(tr("账号:"), m_usernameEdit);
    formLayout->addRow(tr("密码:"), m_passwordEdit);

    // 创建按钮布局
    QHBoxLayout *btnLayout = new QHBoxLayout();
    btnLayout->addWidget(m_loginBtn);
    btnLayout->addWidget(m_cancelBtn);
btnLayout->setSpacing(15);

    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(formLayout);
    mainLayout->addLayout(btnLayout);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

    setLayout(mainLayout);

    // 连接信号槽
    connect(m_loginBtn, &QPushButton::clicked, this, &LoginDialog::onLoginClicked);
    connect(m_cancelBtn, &QPushButton::clicked, this, &LoginDialog::onCancelClicked);
}

void LoginDialog::onLoginClicked()
{
    QString username = m_usernameEdit->text().trimmed();
    QString password = m_passwordEdit->text();

    // 验证输入
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, tr("输入错误"), tr("用户名和密码不能为空"));
        return;
    }

    // 密码哈希处理
    QString hashedPassword = Utils::sha256(password);

    // 查询用户
    QList<QVariantList> data;
    QHash<QString, QVariant> where;
    where.insert("account", username);
    where.insert("password", hashedPassword);

    if (m_sqlOperator->selectData("user", {"account"}, where, data) && !data.isEmpty()) {
        emit loginSuccess(username);
        accept();
        widget_view->show();
        //this->hide();
    } else {
        QMessageBox::warning(this, tr("登录失败"), tr("用户名或密码错误"));
    }
}

void LoginDialog::onCancelClicked()
{
    reject();
}

